package com.cristina.attention.dispatcher;

import com.alibaba.fastjson.JSON;
import com.cristina.attention.codec.Invocation;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import java.util.concurrent.*;

import static io.netty.handler.codec.http.HttpUtil.isKeepAlive;

/**
 * 消息分发.
 * SimpleChannelInboundHandler 是 Netty 定义的消息处理 ChannelHandler 抽象类，处理消息的类型是 <I> 泛型。
 * <pre>
 * - 调用 {@link MessageHandlerContainer#getMessageHandler(String type)} 方法，获得
 * Invocation 的 type 对应的 MessageHandler 处理器
 * - 调用 {@link MessageHandlerContainer#getMessageClass(messageHandler)} 方法,
 * 获得 MessageHandler 处理器的消息类
 * - 将 Invocation 的 message 解析成 MessageHandler 对应的消息对象
 * - 放到线程池中，然后调用 {@link MessageHandler#execute(Channel channel, T message)} 方法，执行业务逻辑
 * </pre>
 * @author superMan
 */
@ChannelHandler.Sharable
@Slf4j
public class MessageDispatcher extends SimpleChannelInboundHandler<Object> {

    private final String TYPE = "AUTHORIZATION";
    private static final String WEBSOCKET = "websocket";
    private static final String UPGRADE = "Upgrade";

    @Value("{netty.websocket.address}")
    private String webSocketURL;

    @Resource
    private MessageHandlerContainer messageHandlerContainer;

    private WebSocketServerHandshaker handshake;

    private ExecutorService executor = new ThreadPoolExecutor(200,200,
            1L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(1024),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy());

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object obj) {
        // 以http请求形式接入，但是走的是websocket
        if (obj instanceof FullHttpRequest) {
            handleHttpRequest(ctx, (FullHttpRequest) obj);

          // 处理 websocket 客户端的消息
        } else if (obj instanceof WebSocketFrame){
            handlerWebSocketFrame(ctx, (WebSocketFrame) obj);
        }

    }

    /**
     * 处理 Http 请求, 完成 websocket 握手
     * <pre>注意: websocket连接第一次请求使用的是 Http</pre>
     * @param ctx
     * @param req
     */
    private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
        // Http 解码失败, 返回异常
        if (!req.decoderResult().isSuccess() || (!WEBSOCKET.equals(req.headers().get(UPGRADE)))) {
            //若不是websocket方式，则创建BAD_REQUEST的req，返回给客户端
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
            return;
        }

        // 正常 websocket 的 Http 连接请求, 构造握手响应返回.
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(webSocketURL, null, false);
        handshake = wsFactory.newHandshaker(req);

        // 无法处理的 websocket 版本
        if (handshake == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        } else {
            // 向客户端发送 websocket 握手, 完成握手.
            handshake.handshake(ctx.channel(), req);
            // ResponseMessage response = new ResponseMessage()
            //         .setCode(HttpResponseStatus.OK.code())
            //         .setMessage(HttpResponseStatus.OK.reasonPhrase());
            //
            // ctx.channel().writeAndFlush(MessageTemplate.sendMessageFormat(TYPE, response));
        }
    }

    /**
     * 处理 websocket 请求
     * @param ctx
     * @param frame
     */
    private void handlerWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame){
        // 判断是否是关闭链路的指令
        if (frame instanceof CloseWebSocketFrame) {
            handshake.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            return;
        }
        // 判断是否ping消息
        if (frame instanceof PingWebSocketFrame) {
            ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
            return;
        }

        // 当前只支持文本消息，不支持二进制消息
        if (!(frame instanceof TextWebSocketFrame)) {
            log.info("不支持二进制消息");
            throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName()));
        }

        String request = ((TextWebSocketFrame) frame).text();
        messageDispatcher(ctx, request);
    }

    /**
     *
     * @param ctx
     * @param req
     * @param res
     */
    private static void sendHttpResponse(ChannelHandlerContext ctx,
                                         FullHttpRequest req, DefaultFullHttpResponse res) {
        // 返回应答给客户端
        if (res.status().code() != HttpResponseStatus.OK.code()) {
            ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(),CharsetUtil.UTF_8);
            res.content().writeBytes(buf);
            buf.release();
        }
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        // 如果是非Keep-Alive，关闭连接
        if (!isKeepAlive(req) || res.status().code() !=  HttpResponseStatus.OK.code()) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }

    private void messageDispatcher(ChannelHandlerContext ctx, String msg) {
        Invocation invocation = JSON.parseObject(msg, Invocation.class);
        // 获得 type 对应的 MessageHandler 处理器
        MessageHandler messageHandler = messageHandlerContainer.getMessageHandler(invocation.getType());
        // 获得  MessageHandler 处理器 的消息类
        Class<? extends Message> messageClass = MessageHandlerContainer.getMessageClass(messageHandler);
        // 解析消息
        Message message = JSON.parseObject(invocation.getMessage(), messageClass);
        // 执行逻辑
        executor.submit(new Runnable() {
            @Override
            public void run() {
                // noinspection unchecked
                messageHandler.execute(ctx.channel(), message);
            }
        });
    }

}
